﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Windows;

namespace jcc
{
    public class StandardWebService
    {
        private static net.metroeguide.Service _service;
        public static net.metroeguide.Service WebService
        {
            get
            {
                if (_service == null)
                {
                    try
                    {
                        _service = new net.metroeguide.Service();
                        return _service;
                    }
                    catch
                    {
                        MessageBox.Show("Fatal Error: Unable to create WebService object.");
                        Application.Current.Shutdown();
                        return null;
                    }
                }
                else
                    return _service;
            }
        }

        public static string GetKey()
        {
            string Key, toHash, Token;

            try
            {
                Token = WebService.GetToken();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to Get Token from the JetNett WebService (server didn't return a response).  This could possibly be of clogged/slow internet.  Clicking OK will force the application to try again, if the second attempt fails, the application will crash :-(.  Good Luck! The Exact exception message follows:\n\n" + ex.ToString());
                Token = WebService.GetToken();
            }
            

            toHash = Login.Username.ToUpper() + "|" + Login.Password.ToUpper() + "|" + Token;

            // Hash(Username|Password|WebServiceToken)|Username
            Key = Hash(toHash) + "|" + Login.Username.ToUpper();
            return Key;
        }
        private static string Hash(string ToHash)
        {
            Encoder enc = System.Text.Encoding.ASCII.GetEncoder();

            byte[] data = new byte[ToHash.Length];
            enc.GetBytes(ToHash.ToCharArray(), 0, ToHash.Length, data, 0, true);

            MD5 md5 = new MD5CryptoServiceProvider();

            byte[] result = md5.ComputeHash(data);

            return BitConverter.ToString(result).Replace("-", "").ToLower();
        }
    }
}
